package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysUser;
import com.powernode.domain.SysUserRole;
import com.powernode.mapper.SysUserMapper;
import com.powernode.mapper.SysUserRoleMapper;
import com.powernode.service.SysUserRoleService;
import com.powernode.service.SysUserService;
import com.powernode.util.AuthUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 贺
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-07-16 19:35:11
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 新增管理员
     * 新增管理员和角色的关系
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        // 新增管理员
        // 补充属性
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        // 当前项目默认店铺ID为1
        sysUser.setShopId(1L);
        // 密码加密
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        int i = sysUserMapper.insert(sysUser);
        if (i > 0) {
            // 获取新增管理员的ID
            Long userId = sysUser.getUserId();
            // 新增管理员和角色的关系
            // 获取管理员角色ID集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            // 判断管理员角色ID集合是否为空
            if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() > 0) {
                // 循环遍历管理员角色ID集合
                // 创建管理员和角色的关系对象集合
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    // 新增管理员和角色的关系
                    // 不建议在循环中操作数据库
                    // sysUserRoleMapper.insert(sysUserRole);
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量新增管理员和角色的关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return i;
    }

    @Override
    public SysUser querySysUserInfoByUserId(Long id) {
        // 根据管理员ID查询管理员信息
        SysUser sysUser = sysUserMapper.selectById(id);
        List<Long> roleIdList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(sysUser)) {
            // 根据管理员ID查询管理员与角色的关系列表
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id));
            if (CollectionUtil.isNotEmpty(sysUserRoles) && sysUserRoles.size() > 0) {
                roleIdList = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            }
        }
        sysUser.setRoleIdList(roleIdList);
        return sysUser;
    }

    /**
     * 修改管理员信息
     * 1. 修改管理员信息
     * 2. 删除管理员与角色的关系
     * 3. 添加管理员与角色的关系
     *
     * @param sysUser
     * @return
     */
    @Override
    public Integer modifySysUserInfo(SysUser sysUser) {
        // 修改管理员信息
        String newPassword = sysUser.getPassword();
        if (StringUtils.hasText(newPassword)) {
            sysUser.setPassword(bCryptPasswordEncoder.encode(newPassword));
        }
        int i = sysUserMapper.updateById(sysUser);
        if (i > 0) {
            // 删除管理员与角色的关系
            sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUser.getUserId()));
            // 添加管理员与角色的关系
            // 获取管理员角色ID集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            // 判断管理员角色ID集合是否为空
            if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() > 0) {
                // 循环遍历管理员角色ID集合
                // 创建管理员和角色的关系对象集合
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(roleId);
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量新增管理员和角色的关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return i;
    }

    /**
     * 批量/单个删除管理员信息
     * 1. 批量/单个删除管理员与角色关系记录
     * 2. 批量/单个删除管理员记录
     *
     * @param userIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysUsersByUserIds(List<Long> userIds) {
        // 批量/单个删除管理员与角色关系记录
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, userIds));

        // 批量/单个删除管理员记录
        return sysUserMapper.deleteBatchIds(userIds) == userIds.size();
    }
}




